package logic

import (
	"context"
	"fmt"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/resultx"
	"mall/service/backend/common/i18n"
	enum "mall/service/backend/common/enum/user"
	"mall/service/user/model"
	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/types/user"

	"github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type SetMemberMetaLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSetMemberMetaLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SetMemberMetaLogic {
	return &SetMemberMetaLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SetMemberMetaLogic) SetMemberMeta(in *user.SetMemberMetaReq) (*user.BaseResp, error) {
	if len(in.TaskMeta) == 0 || in.TaskName == nil || len(*in.TaskName) == 0 {
		return &user.BaseResp{}, nil
	}

	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, resultx.StatusError(resultx.DB_ERROR, "")
	}

	var taskGem uint32
	if in.TaskGem != nil && *in.TaskGem > 0 {
		taskGem = *in.TaskGem
	}
	now := time.Now()
	var gemUids []uint64
	for _, v := range in.TaskMeta {
		var uid uint64 // 用户ID
		if v.Id != nil && *v.Id > 0 {
			uid = *v.Id
		}
		if v.Uid != nil && *v.Uid > 0 { // 香评ID、
			log := &model.UserTaskLog{
				UserID:    uid,
				TaskSlug:  *in.TaskName,
				Status:    uint8(globalkey.StatusEnabled),
				CreatedAt: now,
				UpdatedAt: now,
			}
			err := l.svcCtx.CurrentUser.InsertTaskLog(l.ctx, tx, log)
			if err != nil {
				logrus.Info(fmt.Sprintf("SetMemberMeta InsertTaskLog err: %+v", err))
				tx.Rollback()

				return nil, err
			}

			if taskGem > 0 {
				var desc string
				if v.Key != nil && len(*v.Key) > 0 {
					desc += *v.Key + " "
				}
				if v.Value != nil && len(*v.Value) > 0 {
					desc += *v.Value
				}
				transLog := &model.UserTransactionLog{
					UserID:       uid,
					AssetType:    uint8(enum.UserAssetTypeGem),
					ChangeType:   uint8(enum.UserAssetChangeTypeIncrease),
					ChangeAmount: strconv.FormatInt(int64(taskGem), 10),
					SourceType:   uint8(enum.UserAssetSourceTypeTask),
					SourceID:     *v.Uid,
					Desc:         strings.TrimSpace(desc),
					Status:       uint8(globalkey.StatusEnabled),
					CreatedAt:    now,
					UpdatedAt:    now,
				}
				err = l.svcCtx.CurrentUser.InsertTransactionLog(l.ctx, tx, transLog)
				if err != nil {
					logrus.Info(fmt.Sprintf("SetMemberMeta InsertTransactionLog err: %+v", err))
					tx.Rollback()

					return nil, err
				}

				gemUids = append(gemUids, uid)
			}
		}
	}

	if taskGem > 0 && len(gemUids) > 0 {
		err = l.svcCtx.CurrentUser.IncreaseBalanceBatch(l.ctx, tx, gemUids, int(taskGem))
		if err != nil {
			logrus.Info(fmt.Sprintf("SetMemberMeta IncreaseBalanceBatch err: %+v", err))
			tx.Rollback()

			return nil, err
		}
	}

	tx.Commit()

	return &user.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
